<script lang="ts" setup>
import { computed, reactive, ref } from 'vue';
import dayjs from 'dayjs'

// typescript
const state = reactive({
  avatarUrl: "../../static/images/default/avatar.png",
  maxDate: dayjs().format("YYYY-MM-DD")
});
const sexItems = ref([
  {text: "男", value: 0},
  {text: "女", value: 1},
  {text: "保密", value: 2}
]);
const user = reactive({
  username: "张三丰",
  nickname: "爱购物",
  sex: 0,
  birthday: "2000-01-01"
});
const getSex = computed(() => {
  return sexItems.value.find(x => x.value == user.sex)?.text;
});

// 性别选择器
const onSexPickerChange = (ev: any) => {
  user.sex = ev.detail.value;
}

// 日期选择器
const onDatePickerChange = (ev: any) => {
  user.birthday = ev.detail.value;
}

// 打开相册或拍照
const onChooseImage = () => {
  uni.chooseImage({
    count: 1,
    success(ev) {
      if (!ev.tempFilePaths[0]) {
        return
      }
      state.avatarUrl = ev.tempFilePaths[0];
    },
    fail(ev) {
      if (ev?.code == 12) {
        return
      }
      uni.showToast({ title: '操作失败', icon: "error" });
    }
  });
}
</script>

<!-- 账号资料 -->
<template>
  <view class="container">
    <!-- 头像 -->
    <view class="avatar-view">
      <view class="avatar" @click="onChooseImage">
        <image :src="state.avatarUrl"></image>
      </view>
    </view>
    <!-- 信息 -->
    <uni-list>
      <uni-list-item show-arrow title="姓名" :right-text="user.username"></uni-list-item>
      <uni-list-item show-arrow title="昵称" :right-text="user.nickname"></uni-list-item>
      <picker range-key="text" :range="sexItems" @change="onSexPickerChange">
        <uni-list-item show-arrow title="性别" :right-text="getSex"></uni-list-item>
      </picker>
      <picker :value="user.birthday" :end="state.maxDate" mode="date" @change="onDatePickerChange">
        <uni-list-item show-arrow title="生日" :right-text="user.birthday"></uni-list-item>
      </picker>
    </uni-list>
  </view>
</template>

<style scoped lang="scss">
// scss
.avatar-view {
  padding: 80rpx 0;

  .avatar {
    width: 148rpx;
    height: 148rpx;
    margin: 0 auto;

    image {
      width: 100%;
      height: 100%;
      border-radius: 50%;
    }
  }
}
</style>
